package com.daka.tools.wechatPay;

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.Map;


public class PayRefundAPI {

    private static Logger LOGGER = LoggerFactory.getLogger(PayRefundAPI.class);

    protected static Header xmlHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE,
            ContentType.APPLICATION_XML.toString());

    /**
     * Send pay refund to wechat
     *
     * @param refund
     * @param key
     * @return
     */
    public static RefundResult payRefund(Refund refund, String key) {
        Map<String, String> map = MapUtil.objectToMap(refund);
        if (null != key) {
            refund.setSign(SignatureUtil.generateSign(map, key));
        }
        String refundXML = XMLConvertUtil.convertToXML(refund);
        LOGGER.info("/PayRefundAPI/pay/refund, refundXML " + refundXML);
        HttpUriRequest request = RequestBuilder.post().setHeader(xmlHeader)
                .setUri("/pay/refund")
                .setEntity(new StringEntity(refundXML, Charset.forName("utf-8"))).build();
        RefundResult result = LocalHttpClient.executeXmlResult(request, RefundResult.class);
        LOGGER.info("/PayRefundAPI/pay/refund, result " + result);
        return result;
    }
}
